package com.dzt.androidframework.database.addedittask;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.dzt.androidframework.R;
import com.dzt.androidframework.activity.ActivityTitle;
import com.dzt.androidframework.database.tasks.TasksLocalDataSource;

public class AddEditActivity extends ActivityTitle {
	public static final String SHOULD_LOAD_DATA_FROM_REPO_KEY = "SHOULD_LOAD_DATA_FROM_REPO_KEY";
	private AddEditPresenter addEditPresenter;
	private AddEditFragment addEditFragment;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_add_edit;
	}

	@Override
	protected void initParams() {
		setTitleView(R.string.add_task);
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		addEditFragment = new AddEditFragment();
		ft.add(R.id.contentFrame, addEditFragment);
		ft.commitAllowingStateLoss();
		String taskId = getIntent().getStringExtra(
				AddEditFragment.ARGUMENT_EDIT_TASK_ID);

		boolean shouldLoadDataFromRepo = true;

		// Prevent the presenter from loading data from the repository if this is a config change.
		if (savedInstanceState != null) {
			// Data might not have loaded when the config change happen, so we saved the state.
			shouldLoadDataFromRepo = savedInstanceState.getBoolean(SHOULD_LOAD_DATA_FROM_REPO_KEY);
		}
		TasksLocalDataSource localDataSource = TasksLocalDataSource.getInstance();
		addEditPresenter = new AddEditPresenter(taskId, localDataSource, addEditFragment,
				shouldLoadDataFromRepo);
		addEditFragment.setPresenter(addEditPresenter);
	}

	@Override
	protected void initData(Bundle savedInstanceState) {

	}

	@Override
	protected String[] initPermissions() {
		return null;
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// Save the state so that next time we know if we need to refresh data.
		outState.putBoolean(SHOULD_LOAD_DATA_FROM_REPO_KEY, addEditPresenter.isDataMissing());
		super.onSaveInstanceState(outState);
	}

	@Override
	public boolean onSupportNavigateUp() {
		onBackPressed();
		return true;
	}

}
